package cn.honqun.tinycms.controller;

import cn.honqun.tinycms.common.exce.ApplicationException;
import cn.honqun.tinycms.constants.ContentTypes;
import cn.honqun.tinycms.domain.entity.FileObject;
import cn.honqun.tinycms.service.FileObjectService;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.net.URLEncodeUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
@Slf4j
public class FileObjectController {
    private final FileObjectService fileObjectService;

    @PostMapping("/create")
    public FileObject create(MultipartFile file) {
        if (file == null) {
            throw new ApplicationException("请选择文件");
        }
        return fileObjectService.create(file);
    }

    @GetMapping("/{path}")
    public void read(@PathVariable String path, HttpServletResponse response) throws IOException {
        FileObject fileObject = fileObjectService.selectByURI(path);
        if (fileObject == null) {
            throw new ApplicationException("文件不存在 " + path);
        }
        setResponse(fileObject, response); //设置文件下载的Headers
        this.fileObjectService.read(path, response.getOutputStream());
    }

    @PostMapping("/remove")
    public void remove(@RequestBody FileObject fileObject) {
        fileObjectService.remove(fileObject.getUrl() != null ? fileObject.getUrl() : fileObject.getUri());
    }

    private void setResponse(FileObject fileObject, HttpServletResponse response) {
        String filename = fileObject.getOriginalName();
        URLEncodeUtil.encode(filename, StandardCharsets.UTF_8); // 支持中文文件名
        response.setContentLengthLong(fileObject.getSize());
        response.setContentType(ContentTypes.getByName(filename));

        if (!FileNameUtil.isType(filename, "jpg", "png", "jpeg")) { //如果不是图片，则下载
            response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        }
    }
}
